//
//  PersonViewController.m
//  EconomyDemo
//
//  Created by qianfeng01 on 15-7-7.
//  Copyright (c) 2015年 xiangmu. All rights reserved.
//

#import "PersonViewController.h"
#import "AFNetworking.h"
#import "PictureModel.h"
#import "PictureCell.h"
#import "TopView.h"
#import "JHRefresh.h"
#import "PersonDetailViewController.h"

#define kUrl @"http://ipadnews.caijing.com.cn/api/1.0/articles.php?bundleId=cn.com.caijing.android&platform=android4.4.2&appVer=2.4.1&network=wifi&action=articlelist&username=&columnId=331&password=&page=%ld"
#define kScreenSize [UIScreen mainScreen].bounds.size
@interface PersonViewController () <UITableViewDataSource,UITableViewDelegate>
{
    AFHTTPRequestOperationManager *_manager;
    NSMutableArray *_dataArray;
    UITableView *_tableView;
    NSMutableArray *_imageNames;
    NSMutableArray *_titleNames;
}
@property (nonatomic,strong) AFHTTPRequestOperationManager *manager;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) TopView *scrollerView;
@property (nonatomic,strong) UIPageControl *pageControl;
@property (nonatomic) NSInteger currentPage;
@property (nonatomic)BOOL isRefreshing;
@property (nonatomic)BOOL isLoadMore;

@end

@implementation PersonViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _manager=[[AFHTTPRequestOperationManager alloc] init];
    _manager.responseSerializer=[AFHTTPResponseSerializer serializer];

    _dataArray=[[NSMutableArray alloc] init];
    [self creatTableView];
    [self firstDownload];
    [self creatRefreshView];
}
- (void)creatRefreshView {
    __weak typeof (self) weakSelf = self;
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (weakSelf.isRefreshing) {
            return ;
        }
        weakSelf.isRefreshing = YES;
       [weakSelf firstDownload];
        
    }];
    [self.tableView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (weakSelf.isLoadMore) {
            return ;
        }
        weakSelf.isLoadMore = YES;
        weakSelf.currentPage ++;
        [weakSelf addTaskWithUrl:[NSString stringWithFormat:kUrl,weakSelf.currentPage] isRefresh:YES];
    }];
    
}
- (void)endRefreshing {
    if (self.isRefreshing) {
        self.isRefreshing = NO;
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultNone];
    }
    if (self.isLoadMore) {
        self.isLoadMore = NO;
        [self.tableView footerEndRefreshing];
    }
}

- (void)firstDownload {
    self.currentPage = 1;
    __weak typeof(self) weakSelf=self;
    [weakSelf.manager GET:[NSString stringWithFormat:kUrl,self.currentPage] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"成功下载");
        if (responseObject) {
            if (weakSelf.currentPage==1) {
                [weakSelf.dataArray removeAllObjects];
            }
        NSArray *arr=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            _imageNames=[[NSMutableArray alloc] init];
            _titleNames=[[NSMutableArray alloc] init];
            NSString *imageStr=[NSString stringWithFormat:@"%@/%@",arr[0][@"path"],arr[0][@"thumbnails_url"][4]];
            NSString *titleStr=arr[0][@"title"];
            [_imageNames addObject:imageStr];
            [_titleNames addObject:titleStr];
            [weakSelf addScrollView:_imageNames title:_titleNames];
         for (NSInteger i=1; i<arr.count; i++) {
                NSDictionary *dict=[[NSDictionary alloc] init];
                dict=arr[i];
                PictureModel *model=[[PictureModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                model.articleId=dict[@"articleId"];
                model.title=dict[@"title"];
                model.description=dict[@"description"];
                model.path=dict[@"path"];
            model.thumbnails_url=dict[@"thumbnails_url"][0];
             
              [weakSelf.dataArray addObject:model];
            }
            [self.tableView reloadData];
            [self endRefreshing];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"下载失败");
    }];
}

-(void)addTaskWithUrl:(NSString *)url isRefresh:(BOOL)isRefresh{
    __weak typeof(self) weakSelf=self;
       [weakSelf.manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"成功下载");
        if (responseObject) {
            if (weakSelf.currentPage==1) {
                [weakSelf.dataArray removeAllObjects];
            }
            
            NSArray *arr=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            for (NSInteger i=0; i<arr.count; i++) {
                NSDictionary *dict=[[NSDictionary alloc] init];
                dict=arr[i];
                PictureModel *model=[[PictureModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                model.articleId=dict[@"articleId"];
                model.title=dict[@"title"];
                model.description=dict[@"description"];
                model.path=dict[@"path"];
                if ([dict[@"thumbnails_url"][0] isEqualToString:@""]==YES) {
                    model.thumbnails_url=dict[@"thumbnails_url"][1];
                }else{
                    model.thumbnails_url=dict[@"thumbnails_url"][0];
                }

                [weakSelf.dataArray addObject:model];
            }
            [self.tableView reloadData];
            [self endRefreshing];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"下载失败");
    }];
    
}
-(void)creatTableView{
    
    _tableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height-49-64) style:UITableViewStylePlain];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [self.view addSubview:_tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"PictureCell" bundle:nil] forCellReuseIdentifier:@"PictureCell"];
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PictureCell *cell=[tableView dequeueReusableCellWithIdentifier:@"PictureCell" forIndexPath:indexPath];
    PictureModel *model=self.dataArray[indexPath.row];
   
    [cell showDataWithModel:model];
    return cell;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    PersonDetailViewController *controller=[[PersonDetailViewController alloc] init];
    PictureModel *model=self.dataArray[indexPath.row];
    controller.articleId=model.articleId;
     controller.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:controller animated:YES];
}

@end
